import axios from "axios";
import router from '@/router'
import store from '../store'
import { Notify } from 'vant';
import { getCookie } from "@/util/cookie";


const instance = axios.create({
    timeout: 600000
})
const token = getCookie('token')

//请求拦截
instance.interceptors.request.use(config => {
    //以该字符串分割获取url
    let url = config.url.split("/api")[1]
    switch (url) {
        case '/cart/add':
            if (token == null) {
                Notify({
                    type: 'danger', message: '请登录', duration: 1500,
                });
                setTimeout(() => router.push('/user'), 1500)

                return Promise.reject('error')
            }
            break;
        case '/address/list': case '/region/list':
        case '/address/delete': case '/address/detail':
        case '/address/save':
            // 拦截设置请求头
            config.headers['X-Nideshop-Token'] = token

            break;

    }
    return config
}, err => {
    return Promise.reject(err)
})

//响应拦截
instance.interceptors.response.use(result => {
    let url = result.config.url.split("/api")[1]
    switch (url) {
        case '/cart/goodscount':
            if (!token) {
                let data = {
                    data: {
                        cartTotal: { goodsCount: 0 }
                    }
                }
                return data;
            }
            break;
    }
    return result.data;
}, err => {
    return Promise.reject(err)
})

export default instance;